package com.gable.exhibition.util;

import com.gable.common.util.CacheData;
import com.gable.common.util.StringUtil;
import com.gable.exhibition.dao.CheckExeclDao;
import com.gable.exhibition.model.ContractDevice;
import com.gable.exhibition.view.ImportExcelContractModel;
import com.gable.exhibition.view.ImportExcelHospitalModel;
import com.gable.exhibition.view.ImportExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Lesson on 2018/2/24.
 */
@Component
public class CheckImportExcelContract {

    @Autowired
    CheckExeclDao checkExeclDao;

    public static String [] properties = new String [] {
            "contractNo","contractName","hospitalCode","supplierNo","contractTypeName","hospitalContacts","hospitalPhone",
            "supplierContacts","supplierPhone","signDate","contractAmountStr","contractRemark","deviceName","deviceModel","placeOrigin",
            "specifications","priceStr","quantityStr","attachment","upkeepCycleStr","maintainerNo","whetherNeedInstallStr","deviceWarrantyPeriodStr",
            "manufacturerNo","supplierWarrantyPeriodStr"};

    private String REGNUMBER = "^[0-9]\\d*(\\.\\d{1,2})?$";

    private String REGINTEGER = "^\\+?[0-9]\\d*$";

    private String REGDATE = "^((((1[6-9]|[2-9]\\d)\\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\\d|3[01]))|(((1[6-9]|[2-9]\\d)\\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\\d|30))|(((1[6-9]|[2-9]\\d)\\d{2})-0?2-(0?[1-9]|1\\d|2[0-8]))|(((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$";



    //用户id作为key
    public static Map<Long,Object> resultMap = new ConcurrentHashMap<Long,Object>();


    public static Map<Long,Object> resultMap1 = new ConcurrentHashMap<Long,Object>();



    public ImportExcelView checkContract(List<ImportExcelContractModel> list ){
        //给到客户端的数据集
        ImportExcelView iev = new ImportExcelView();

        //错误信息
        List<String> errorMessage = new ArrayList<String>();

        int count=0;

        Map map = new HashMap();

        Map<String,Integer> contractNoMap = new HashMap<String,Integer>();

        Map<String,Integer> deviceModelMap = new HashMap<String,Integer>();

        List<ContractDevice>  contractDeviceList = new ArrayList<ContractDevice>();

        List<ImportExcelContractModel> lists = new ArrayList<ImportExcelContractModel>();
        for(int i = 0;i < list.size();i++) {
            int row = i + 1;

            //校验合同编号 (默认合同编号是唯一)
            if(StringUtil.isEmpty(list.get(i).getContractNo())){
                errorMessage.add("第"+row+"行，第"+queryProperties("contractNo")+"列的合同编号信息不能为空");
                count++;
            }else{
                int result = checkExeclDao.checkContractNo(list.get(i).getContractNo());
                if(result>0){
                    errorMessage.add("第"+row+"行，第"+queryProperties("hospitalName")+"列的合同编号已存在");
                    count++;
                }
            }

            //校验甲方，--医院
            if(StringUtil.isEmpty(list.get(i).getHospitalCode())){
                errorMessage.add("第"+row+"行，第"+queryProperties("hospitalCode")+"列的甲方信息不能为空");
                count++;
            }else{
                Long hospitalId = checkExeclDao.queryHospitalIdByHospitalCode(list.get(i).getHospitalCode());
                if(hospitalId == null){
                    errorMessage.add("第"+row+"行，第"+queryProperties("hospitalCode")+"列的甲方信息不存在");
                    count++;
                }else{
                    list.get(i).setHospitalId(hospitalId);
                }
            }

            //校验乙方, -- 厂家
            if(StringUtil.isEmpty(list.get(i).getSupplierNo())){
                errorMessage.add("第"+row+"行，第"+queryProperties("supplierNo")+"列的乙方信息不能为空");
                count++;
            }else{
                Long supplierId = checkExeclDao.querySupplierIdByNo(list.get(i).getSupplierNo());
                if(supplierId == null){
                    errorMessage.add("第"+row+"行，第"+queryProperties("supplierNo")+"列的乙方信息不存在");
                    count++;
                }else{
                    list.get(i).setSupplierId(supplierId);
                }
            }

            //校验合同类型
            if(!StringUtil.isEmpty(list.get(i).getContractTypeName())){
                Long id = checkExeclDao.checkContractType(list.get(i).getContractTypeName());
                if(id == null){
                    errorMessage.add("第"+row+"行，第"+queryProperties("contractTypeName")+"列的合同类型不存在");
                    count++;
                }else{
                    list.get(i).setContractType(id);
                }
            }

         /*   //校验设备保修期(月)
            if(!StringUtil.isEmpty(list.get(i).getDeviceWarrantyPeriodStr())){
                boolean bl = CheckPattern(REGINTEGER,list.get(i).getDeviceWarrantyPeriodStr());
                if(!bl){
                    errorMessage.add("第"+row+"行，第"+queryProperties("deviceWarrantyPeriodStr")+"列的设备保修期(月)格式不正确");
                    count++;
                }else{
                    list.get(i).setDeviceWarrantyPeriod(Integer.parseInt(list.get(i).getDeviceWarrantyPeriodStr()));
                }
            }*/

            //校验签订时间
            if(!StringUtil.isEmpty(list.get(i).getSignDate())){
                boolean bl = CheckPattern(REGDATE,list.get(i).getSignDate());
                if(!bl){
                    errorMessage.add("第"+row+"行，第"+queryProperties("deviceWarrantyPeriodStr")+"列的签订时间格式不正确");
                    count++;
                }
            }

            //校验合同金额
            if(!StringUtil.isEmpty(list.get(i).getContractAmountStr())){
                boolean bl = CheckPattern(REGNUMBER,list.get(i).getContractAmountStr());
                if(!bl){
                    errorMessage.add("第"+row+"行，第"+queryProperties("contractAmountStr")+"列的合同金额格式不正确");
                    count++;
                }else{
                    double price = Double.parseDouble(list.get(i).getContractAmountStr());
                    price = price * 100;
                    list.get(i).setContractAmount((long)price);
                }
            }


            //校验设备型号
            if(StringUtil.isEmpty(list.get(i).getDeviceModel())){
                errorMessage.add("第"+row+"行，第"+queryProperties("deviceModel")+"列的设备型号不能为空");
                count++;
            }else{
                String key = list.get(i).getContractNo() + list.get(i).getDeviceModel();
                if(deviceModelMap.containsKey(key)){
                    errorMessage.add("第"+row+"行，第"+queryProperties("deviceModel")+"列的设备型号和"+"第"+deviceModelMap.get(key)+"行，"+"第"+queryProperties("deviceModel")+"列的设备型号相同");
                    count++;
                }else{
                    deviceModelMap.put(key,row);
                }
            }

            //校验设备单价
            if(StringUtil.isEmpty(list.get(i).getPriceStr())){
                errorMessage.add("第"+row+"行，第"+queryProperties("quantityStr")+"列的单价不能为空");
                count++;
            }else{
                boolean bl = CheckPattern(REGNUMBER,list.get(i).getPriceStr());
                if(!bl){
                    errorMessage.add("第"+row+"行，第"+queryProperties("priceStr")+"列的单价格式不正确");
                    count++;
                }else{
                    double price = Double.parseDouble(list.get(i).getPriceStr());
                    price = price * 100;
                    list.get(i).setPrice((long)price);
                }
            }

            //校验设备数量
            if(StringUtil.isEmpty(list.get(i).getQuantityStr())){
                errorMessage.add("第"+row+"行，第"+queryProperties("quantityStr")+"列的数量不能为空");
                count++;
            }else{
                boolean bl = CheckPattern(REGINTEGER,list.get(i).getQuantityStr());
                if(!bl){
                    errorMessage.add("第"+row+"行，第"+queryProperties("quantityStr")+"列的数量格式不正确");
                    count++;
                }else{
                    list.get(i).setQuantity(Integer.parseInt(list.get(i).getQuantityStr()));
                }
            }

            //校验保养周期(月)
            if(!StringUtil.isEmpty(list.get(i).getUpkeepCycleStr())){
                boolean bl = CheckPattern(REGINTEGER,list.get(i).getUpkeepCycleStr());
                if(!bl){
                    errorMessage.add("第"+row+"行，第"+queryProperties("upkeepCycleStr")+"列的保养周期(月)格式不正确");
                    count++;
                }else{
                    list.get(i).setUpkeepCycle(Integer.parseInt(list.get(i).getUpkeepCycleStr()));
                }
            }

            //校验维修商
            if(!StringUtil.isEmpty(list.get(i).getMaintainerNo())){
                   Long maintainerId = checkExeclDao.queryMaintainerIdByMaintainerNo(list.get(i).getMaintainerNo());
                   if(maintainerId == null){
                       errorMessage.add("第"+row+"行，第"+queryProperties("maintainerNo")+"维修商信息不存在");
                       count++;
                   }else{
                       list.get(i).setMaintainerId(maintainerId);
                   }
            }

            //校验是否需要安装
            if(StringUtil.isEmpty(list.get(i).getWhetherNeedInstallStr())){
                errorMessage.add("第"+row+"行，第"+queryProperties("whetherNeedInstallStr")+"列的是否需要安装不能为空");
                count++;
            }else{
                if(list.get(i).getWhetherNeedInstallStr().equals("是")){
                    list.get(i).setWhetherNeedInstall(1);
                }else if(list.get(i).getWhetherNeedInstallStr().equals("否")){
                    list.get(i).setWhetherNeedInstall(0);
                }else{
                    errorMessage.add("第"+row+"行，第"+queryProperties("whetherNeedInstallStr")+"列的是否需要安装内容错误");
                    count++;
                }
            }

            if(!StringUtil.isEmpty(list.get(i).getManufacturerNo())){
                Long manufacturerId = checkExeclDao.queryManufacturerIdByNo(list.get(i).getManufacturerNo());
                if(manufacturerId == null){
                    errorMessage.add("第"+row+"行，第"+queryProperties("manufacturerNo")+"列的厂家信息不存在");
                    count++;
                }else{
                    list.get(i).setManufacturerId(manufacturerId);
                }
            }

            if(!StringUtil.isEmpty(list.get(i).getDeviceWarrantyPeriodStr())){
                boolean bl = CheckPattern(REGINTEGER,list.get(i).getDeviceWarrantyPeriodStr());
                if(!bl){
                    errorMessage.add("第"+row+"行，第"+queryProperties("deviceWarrantyPeriodStr")+"列的设备厂家保修期(月)格式不正确");
                    count++;
                }else{
                    list.get(i).setDeviceWarrantyPeriod(Integer.parseInt(list.get(i).getDeviceWarrantyPeriodStr()));
                }
            }

            if(!StringUtil.isEmpty(list.get(i).getSupplierWarrantyPeriodStr())){
                boolean bl = CheckPattern(REGINTEGER,list.get(i).getSupplierWarrantyPeriodStr());
                if(!bl){
                    errorMessage.add("第"+row+"行，第"+queryProperties("deviceWarrantyPeriodStr")+"列的设备经销商保修期(月)格式不正确");
                    count++;
                }else{
                    list.get(i).setSupplierWarrantyPeriod(Integer.parseInt(list.get(i).getSupplierWarrantyPeriodStr()));
                }
            }

            ContractDevice contractDevice = new ContractDevice();
            contractDevice.setWhetherNeedInstall(list.get(i).getWhetherNeedInstall());
            contractDevice.setDeviceName(list.get(i).getDeviceName());
            contractDevice.setDeviceModel(list.get(i).getDeviceModel());
            contractDevice.setPlaceOrigin(list.get(i).getPlaceOrigin());
            contractDevice.setSpecifications(list.get(i).getSpecifications());
            contractDevice.setPrice(list.get(i).getPrice());
            contractDevice.setQuantity(list.get(i).getQuantity());
            contractDevice.setAttachment(list.get(i).getAttachment());
            contractDevice.setUpkeepCycle(list.get(i).getUpkeepCycle());
            contractDevice.setMaintainerId(list.get(i).getMaintainerId());
            contractDevice.setRemark(list.get(i).getDeviceRemark());
            contractDevice.setDeviceWarrantyPeriod(list.get(i).getDeviceWarrantyPeriod());
            contractDevice.setManufacturerId(list.get(i).getManufacturerId());
            contractDevice.setSupplierWarrantyPeriod(list.get(i).getSupplierWarrantyPeriod());

            List<ContractDevice>  contractDeviceList1 = new ArrayList<>();
            if(!contractNoMap.containsKey(list.get(i).getContractNo())){
                contractDeviceList = contractDeviceList1;
                lists.add(list.get(i));
                lists.get(i).setContractDeviceList(contractDeviceList);
            }

            contractDeviceList.add(contractDevice);
            contractNoMap.put(list.get(i).getContractNo(),row);
        }

        if(count == 0){
            iev.setBool(true);
        }else{
            iev.setBool(false);
        }

        iev.setErrorMessage(errorMessage);
        CheckImportExcelContract.resultMap1.put(CacheData.getSessionUser(null,1).getUserId(),lists);
        return iev;

    }

    //获取Properties数组字符串的下标
    public int queryProperties(String str){
        if(str == null || str.equals("")){
            return 0;
        }
        for(int i = 0;i<properties.length;i++){
            if(properties[i].equals(str)){
                int index = i+2;
                return index;
            }
        }
        return 0;
    }

    //正则表达式
    public boolean  CheckPattern(String reg,String str){
        str = str .replaceAll("/","-");
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(str);
        boolean bl = matcher.matches();
        return bl;
    }

    //根据Map中的key删除map中的元素
    public static synchronized void removeMap (Map map,Long delKey){
        if(map == null || map.size()==0){
            return;
        }
        Iterator iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            Long key = Long.parseLong(iterator.next().toString());
            if (key.longValue() == delKey.longValue()) {
                map.remove(key);
                break;
            }
        }
    }

}
